package middleware

import (
	"finance/internal/models"
	"github.com/gin-gonic/gin"
	"strings"
	"time"
)

// LogMiddleware 自动记录每次用户请求
func LogMiddleware() gin.HandlerFunc {
	return func(c *gin.Context) {
		c.Next() // 等请求执行完再记录

		// 跳过 OPTIONS 请求(CORS预检)
		if c.Request.Method == "OPTIONS" {
			return
		}

		// 从上下文获取信息
		var userID uint
		if strings.Contains(c.Request.URL.Path, "login") {
			userID = 0 // 未登录用户
		} else {
			userID = c.GetUint("userID")
		}

		ip := c.ClientIP()
		path := c.Request.URL.Path
		status := c.Writer.Status() // http状态码

		log := models.SystemLog{
			UserID:    userID,
			Action:    path,
			IP:        ip,
			Status:    status,
			Detail:    "用户访问了 " + path,
			CreatedAt: time.Now(),
		}

		models.DB.Create(&log)
	}
}
